<?php
// 引入数据库配置
require_once 'config.php';

// 创建用户表
$sql_users = "CREATE TABLE IF NOT EXISTS users (
    id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL UNIQUE,
    password VARCHAR(255) NOT NULL,
    email VARCHAR(100) NOT NULL UNIQUE,
    register_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)";

if ($conn->query($sql_users) === TRUE) {
    echo "用户表创建成功<br>";
} else {
    echo "创建用户表错误: " . $conn->error . "<br>";
}

// 创建商品表
$sql_products = "CREATE TABLE IF NOT EXISTS products (
    id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    price DECIMAL(10,2) NOT NULL,
    description TEXT,
    image VARCHAR(255),
    create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)";

if ($conn->query($sql_products) === TRUE) {
    echo "商品表创建成功<br>";
} else {
    echo "创建商品表错误: " . $conn->error . "<br>";
}

// 创建购物车表
$sql_cart = "CREATE TABLE IF NOT EXISTS cart (
    id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    user_id INT(11) UNSIGNED NOT NULL,
    product_id INT(11) UNSIGNED NOT NULL,
    quantity INT(11) NOT NULL DEFAULT 1,
    add_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    FOREIGN KEY (product_id) REFERENCES products(id) ON DELETE CASCADE
)";

if ($conn->query($sql_cart) === TRUE) {
    echo "购物车表创建成功<br>";
} else {
    echo "创建购物车表错误: " . $conn->error . "<br>";
}

// 插入示例商品数据
$sql_insert_products = "INSERT INTO products (name, price, description, image) VALUES
    ('电影票 - 复仇者联盟', 80.00, '复仇者联盟最新电影票，IMAX 3D体验', 'images/movie1.jpg'),
    ('电影票 - 哪吒闹海', 60.00, '国产动画电影，全新视觉体验', 'images/movie2.jpg'),
    ('电影票 - 唐人街探案', 70.00, '热门喜剧探案电影', 'images/movie3.jpg'),
    ('电影套餐 - 双人票+爆米花', 150.00, '双人电影票加大桶爆米花和饮料', 'images/combo1.jpg'),
    ('电影周卡', 280.00, '一周内无限观影', 'images/card1.jpg')
";

// 检查products表是否为空
$result = $conn->query("SELECT COUNT(*) as count FROM products");
$row = $result->fetch_assoc();

if ($row['count'] == 0) {
    if ($conn->query($sql_insert_products) === TRUE) {
        echo "示例商品数据添加成功<br>";
    } else {
        echo "添加示例商品数据错误: " . $conn->error . "<br>";
    }
} else {
    echo "商品数据已存在，跳过添加示例数据<br>";
}

echo "数据库初始化完成!";
$conn->close();
?> 